//
// video_multi_player.h
//
#pragma once

#include <video_server_common.h>
#include <stdio.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/avstring.h>
#include <SDL.h>
#include <SDL_thread.h>
#include <uthash.h>
#include <packet_queue.h>
#include <time.h>

#ifdef __MINGW32__
#undef main /* Prevents SDL from overriding main() */
#endif

#include <math.h>

#define MAX_VIDEO_PLAYERS 4
#define NUM_PLAYERS_IN_ROW 2
#define NUM_PLAYERS_IN_COL 2

#define SINGLE_SCREEN_WIDTH 320
#define SINGLE_SCREEN_HEIGHT 240

#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)

#define FF_ALLOC_EVENT   (SDL_USEREVENT)
#define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
#define FF_QUIT_EVENT (SDL_USEREVENT + 2)

#define VIDEO_PICTURE_QUEUE_SIZE 50

// A single video player
typedef struct video_single_player_t {
	int				player_id;
	int				is_running;
	int				horizontal_offset;
	int				vertical_offset;

	struct VideoState 		*state;
	SDL_Overlay			*bmp;
	SDL_Rect			rect;
	SDL_Surface			*surface;
	struct video_client_bind_t 	*bind;

	AVCodecContext			*codecCtx;
	AVCodec				*codec;
	AVFrame				*frame;
	int				frame_finished;
	float				aspect_ratio;
	struct SwsContext		*img_convert_ctx;

	PacketQueue			*videoq;
	SDL_Thread			*video_tid;	

	UT_hash_handle			hh;
} video_single_player_t;

// A multiple screen video player
typedef struct video_multi_player_t {
	int				is_running;
	SDL_Event			event;
	SDL_Surface			*screen;
	SDL_Overlay                     *bmp;
	SDL_Rect			rect;
	int				player_positions[MAX_VIDEO_PLAYERS];
	SDL_Thread			*repaint_thread;
	struct video_single_player_t	*video_players;
} video_multi_player_t;

// C'tor
void video_multi_player(struct video_multi_player_t *video_mp);
// Adds a video screen for a newly bounded client
int add_video_player(struct video_multi_player_t *video_mp, struct video_client_bind_t *new_bind);
// Removes a video screen of a leaving client
int remove_video_player(struct video_multi_player_t *video_mp, struct video_client_bind_t *remove_bind);
// Destructor
int stop_all_players(struct video_multi_player_t *player);
